﻿namespace Atomic.Events
{
    using System;
    using System.Diagnostics;
    using System.Reflection;

    using Atomic.Extensions;

    internal class EventState
    {
        internal static readonly MethodInfo CreateEventManagerMethod = typeof(EventState).GetOnlyDeclaredMethod("CreateEventManager");

        private readonly Type _elementType;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="elementType"></param>
        public EventState(Type elementType)
        {
            this._elementType = elementType;
        }

        public Type ElementType 
        {
            get 
            {
                return this._elementType;
            }
        }

        public IEventManager CreateEventManager()
        {
            Debug.Assert(CreateEventManagerMethod != null, "Unable to retrieve EventState.CreateEventManager<> method");

            var genericEventManagerMethod = CreateEventManagerMethod.MakeGenericMethod(_elementType);
            return (IEventManager)genericEventManagerMethod.Invoke(this, new object[0]);
        }

        public IEventManager<TEventType> CreateEventManager<TEventType>() where TEventType : class, IEvent
        {
            Debug.Assert(typeof(TEventType) == ElementType, "Element type mismatch");

            return new DefaultEventManager<TEventType>();
        }
    }
}